<?php
declare (strict_types = 1);

namespace ui;

use exception\FriendlyException;

/**
 * 
 */
class Button {
    public const TYPE_TEXT = 'text';
    public const TYPE_PRIMARY = 'primary';
    public const TYPE_SUCCESS = 'success';
    public const TYPE_DANGER = 'error';
    
    // 打开自定义表单
    public const METHOD_FORM = 'FORM';

    // MESSAGE_BOX对话框
    public const METHOD_MESSAGE_BOX = 'MESSAGE_BOX';

    // POST请求
    public const METHOD_POST = 'POST';

    // Event事件
    public const METHOD_EVENT = 'EVENT';

    // 动作key
    private $action = '';

    private $label = '';

    private $type = self::TYPE_PRIMARY;

    private $method = '';
    private $methodObj = null;

    private $icon = '';

    private $submitFilterKey = '';
    private $submitFilterDateKey = '';

    public function __construct($action) {
        $this->action = $action;
    }

    public static function create($action, $obj) {
        $btn = new Button($action);
        if($obj instanceof MessageBox) {
            $btn->method = self::METHOD_MESSAGE_BOX;
            $btn->methodObj = $obj->build();
        } else if($obj instanceof Form) {
            $btn->method = self::METHOD_FORM;
            $btn->methodObj = $obj->build();
        } else if($obj instanceof Event) {
            $btn->method = self::METHOD_EVENT;
            $btn->methodObj = $obj->build();
        } else if(is_string($obj)) {
            $btn->method = self::METHOD_POST;
            $btn->methodObj = $obj;
        } else {
            throw new FriendlyException("不支持的按钮方法");
        }
        return $btn;
    }

    public static function createSuccess($action, $obj) {
        $btn = self::create($action, $obj);
        $btn->setType(self::TYPE_SUCCESS);
        return $btn;
    }

    public static function createDanger($action, $obj) {
        $btn = self::create($action, $obj);
        $btn->setType(self::TYPE_DANGER);
        return $btn;
    }

    public static function createText($action, $obj) {
        $btn = self::create($action, $obj);
        $btn->setType(self::TYPE_TEXT);
        return $btn;
    }

    public function setLabel($label) {
        $this->label = $label;
        return $this;
    }

    public function setIcon($icon) {
        $this->icon = $icon;
        return $this;
    }

    public function setType($type) {
        $this->type = $type;
        return $this;
    }

    public function setSubmitFilter($key = 'ids', $dataKey = 'id') {
        $this->submitFilterKey = $key;
        $this->submitFilterDateKey = $dataKey;
        return $this;
    }

    public function build() {
        return [
            'action' => $this->action,
            'label' => $this->label,
            'type' => $this->type,
            'method' => $this->method,
            'methodObj' => $this->methodObj,
            'icon' => $this->icon,
            'submitFilterKey' => $this->submitFilterKey,
            'submitFilterDateKey' => $this->submitFilterDateKey,
        ];
    }

}